<template>
  <v-container fluid class="userManagement-container">
    <v-row>
      <!-- 左侧组织树 -->
      <v-col cols="12" md="4" lg="3" xl="3">
        <v-card class="mb-4" elevation="10">
          <v-card-title class="text-subtitle-1 font-weight-medium pa-4" rounded="lg">
            <v-spacer></v-spacer>
            <v-text-field v-model="filterText" placeholder="输入关键字过滤" density="compact" variant="outlined" hide-details
              prepend-inner-icon="mdi-magnify" class="mt-0"></v-text-field>
          </v-card-title>
          <v-card-text class="pa-0" rounded="xl">
            <v-list rounded="xl">
              <template v-for="(item, index) in orgData" :key="item.id">
                <v-list-item :value="item" @click="handleNodeClick(item)"
                  :class="{ 'selected': treeSelection.includes(item.id) }">
                  <v-list-item-title>{{ item.orgName }}</v-list-item-title>
                </v-list-item>

                <v-list v-if="item.children && item.children.length" class="pl-4">
                  <v-list-item v-for="child in item.children" :key="child.id" :value="child"
                    @click="handleNodeClick(child)" :class="{ 'selected': treeSelection.includes(child.id) }">

                    <v-list-item-title>{{ child.orgName }}</v-list-item-title>
                  </v-list-item>
                </v-list>
              </template>
            </v-list>
          </v-card-text>
        </v-card>
      </v-col>

      <!-- 右侧用户列表 -->
      <v-col cols="12" md="8" lg="9" xl="9">
        <!-- 高级搜索 -->
        <v-expand-transition>
          <v-card v-show="moreQueryFlag" class="mb-4" elevation="10">
            <v-card-text>
              <v-row>
                <v-col cols="12" md="6">
                  <v-text-field v-model.trim="queryForm.username_EQ" placeholder="请输入用户名" density="compact"
                    variant="outlined" hide-details clearable prepend-inner-icon="mdi-account"></v-text-field>
                </v-col>
                <v-col cols="12" md="6">
                  <v-text-field v-model.trim="queryForm.no_EQ" placeholder="请输入工号" density="compact" variant="outlined"
                    hide-details clearable prepend-inner-icon="mdi-card-account-details"></v-text-field>
                </v-col>
              </v-row>
            </v-card-text>
          </v-card>
        </v-expand-transition>

        <!-- 工具栏 -->
        <v-card class="mb-4" elevation="10">
          <v-card-text>
            <v-row align="center">
              <v-col cols="12" md="6">
                <v-btn v-if="$perms('system_user_insert')" color="primary" prepend-icon="mdi-plus" @click="handleEdit"
                  class="mr-2">添加</v-btn>
                <v-btn v-if="$perms('system_user_delete')" color="error" prepend-icon="mdi-delete"
                  :disabled="!selectRows.length" @click="handleDelete">批量删除</v-btn>
              </v-col>
              <v-col cols="12" md="6">
                <v-row>
                  <v-col>
                    <v-text-field v-model.trim="queryForm.realName_LIKE" placeholder="请输入昵称" density="compact"
                      variant="outlined" hide-details clearable prepend-inner-icon="mdi-account-search"></v-text-field>
                  </v-col>
                  <v-col cols="auto">
                    <v-btn color="primary" prepend-icon="mdi-magnify" @click="queryData" class="mr-2">查询</v-btn>
                    <v-btn variant="outlined" prepend-icon="mdi-filter-variant" @click="moreQuery">更多</v-btn>
                  </v-col>
                </v-row>
              </v-col>
            </v-row>
          </v-card-text>
        </v-card>

        <!-- 数据表格 -->
        <v-card elevation="10">
          <v-data-table v-model:items-per-page="queryForm.pageSize" :headers="headers" :items="list"
            :loading="listLoading" :items-length="total" @update:options="handleTableUpdate" show-select
            @update:model-value="setSelectRows" class="elevation-0">
            <template v-slot:item.enable="{ item }">
              <v-switch v-if="$perms('system_user_enable')" v-model="item.enable" :true-value="'1'" :false-value="'0'"
                @change="handleEnableAccount(item)" hide-details density="compact" color="success"></v-switch>
            </template>

            <template v-slot:item.actions="{ item }">
              <v-btn v-if="$perms('system_user_update')" variant="text" color="primary" size="small"
                @click="handleEdit(item)" class="mr-2">编辑</v-btn>
              <v-menu>
                <template v-slot:activator="{ props }">
                  <v-btn variant="text" v-bind="props" size="small">
                    更多
                    <v-icon>mdi-chevron-down</v-icon>
                  </v-btn>
                </template>
                <v-list>
                  <v-list-item v-if="$perms('system_user_setOrg')" @click="showOrg(item)"
                    prepend-icon="mdi-account-group">
                    <v-list-item-title>授权组织</v-list-item-title>
                  </v-list-item>
                  <v-list-item v-if="$perms('system_user_setRole')" @click="setRoles(item)"
                    prepend-icon="mdi-shield-account">
                    <v-list-item-title>授权角色</v-list-item-title>
                  </v-list-item>
                  <v-list-item v-if="$perms('system_user_updatePassword')" @click="updatePassword(item)"
                    prepend-icon="mdi-key">
                    <v-list-item-title>修改密码</v-list-item-title>
                  </v-list-item>
                  <v-list-item v-if="$perms('system_user_resetPassword')" @click="resetPassword(item)"
                    prepend-icon="mdi-key-reset">
                    <v-list-item-title>重置密码</v-list-item-title>
                  </v-list-item>
                  <v-list-item v-if="$perms('system_user_delete')" @click="handleDelete(item)" prepend-icon="mdi-delete"
                    color="error">
                    <v-list-item-title>删除</v-list-item-title>
                  </v-list-item>
                </v-list>
              </v-menu>
            </template>
          </v-data-table>
        </v-card>

        <!-- 添加用户按钮 -->
        <v-btn v-if="$perms('system_user_insert')" color="primary" icon="mdi-plus" size="large" class="add-user-btn"
          @click="handleEdit"></v-btn>

        <edit ref="edit" @fetchData="fetchData"></edit>
        <update-password ref="update-password"></update-password>
        <roles ref="roles" @fetchData="fetchData"></roles>
        <user-management-set-org ref="user-management-set-org" :is-gen="isGen"
          @choose="orgMoreChoose"></user-management-set-org>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
import {
  getList, doDelete, doDeleteAll, doResetPasswordById,
  doEnableAccount, doSetOrg, getOrgByUserId
} from "@/api/system/user/userManagement.ts";
import { getTreeByDefWithUserToLike } from "@/api/system/org/orgManagement.ts";
import Edit from "./components/UserManagementEdit.vue";
import Roles from "./components/UserManagementRoles.vue";
import UpdatePassword from "./components/UserManagementPassword.vue";
import UserManagementSetOrg from "./components/UserManagementSetOrg.vue";
import { isNull } from "@/utils/validate";
import { getUserInfo } from "@/api/user.ts";

export default {
  name: "UserManagement",
  components: {
    Edit,
    Roles,
    UpdatePassword,
    UserManagementSetOrg,
  },
  data() {
    return {
      headers: [
        { title: '序号', key: 'index', sortable: false },
        { title: '启用状态', key: 'enable', sortable: false },
        { title: '用户名', key: 'username', sortable: false },
        { title: '昵称', key: 'realName', sortable: false },
        { title: '角色', key: 'roleNames', sortable: false },
        { title: '工号', key: 'no', sortable: false },
        { title: '手机', key: 'mobile', sortable: false },
        { title: '邮箱', key: 'email', sortable: false },
        { title: '最后登录IP', key: 'loginIp', sortable: false },
        { title: '备注', key: 'remark', sortable: false },
        { title: '操作', key: 'actions', sortable: false }
      ],
      activeName: "1",
      userInfo: {
        tenantId: null
      },
      orgNode: null,
      isGen: false,
      list: [],
      listLoading: true,
      total: 0,
      selectRows: [],
      treeSelection: [],
      moreQueryFlag: false,
      queryForm: {
        pageNo: 1,
        pageSize: 10,
        username_EQ: "",
        realName_LIKE: "",
        no_EQ: "",
        orgIdGroup: "org_all",
      },
      filterText: "",
      orgData: [],
      treeLoading: false,
    };
  },
  created() {
    this.getCurrUser();
    this.fetchOrgData();
    this.fetchData();
  },
  watch: {
    filterText(val) {
      // Vuetify treeview 会自动处理过滤
    },
  },
  methods: {
    handleTableUpdate(options) {
      this.queryForm.pageNo = options.page;
      this.queryForm.pageSize = options.itemsPerPage;
      this.fetchData();
    },
    async orgMoreChoose(result, row) {
      if (!row) {
        this.$baseMessage("请选择操作用户", "error");
      }
      const { msg } = await doSetOrg({
        userId: row.id,
        defModel: result.defOrg,
        orgModelList: result.orgList,
      });
      this.$baseMessage(msg, "success");
      await this.fetchData();
    },
    async showOrg(row) {
      const { data } = await getOrgByUserId({
        userId: row.id,
      });
      let defOrgId;
      let checkOrgIds = [];
      if (data && data.length > 0) {
        data.forEach((item) => {
          if ("1" === item.izDef) {
            defOrgId = item.orgId;
          }
          checkOrgIds.push(item.orgId);
        });
      }
      this.$refs["user-management-set-org"]
        .showCheckChoose(checkOrgIds, defOrgId, row);
    },
    setRoles(row) {
      if (!row) {
        this.$baseMessage("请选择操作用户", "error");
      }
      if ('0' === this.userInfo.tenantId &&
        isNull(this.userInfo.switchTenantId)) {
        this.activeName = '0';
      }
      this.$refs['roles'].showRole(row, this.activeName);
    },
    updatePassword(row) {
      if (!row) {
        this.$baseMessage("请选择操作用户", "error");
      }
      this.$refs["update-password"].showUpdatePassword(row);
    },
    resetPassword(row) {
      if (!row) {
        this.$baseMessage("请选择操作用户", "error");
      }
      if (isNull(row.id)) {
        this.$baseMessage('未选择用户', "error");
        return;
      }
      this.$baseConfirm("你确定要重置当前用户密码吗", null, async () => {
        const { msg } = await doResetPasswordById({ userId: row.id });
        this.$baseMessage(msg, "success");
      });
    },
    setSelectRows(val) {
      this.selectRows = val;
    },
    handleEdit(row) {
      if (row.id) {
        this.$refs["edit"].showEdit(row, null);
      } else {
        this.$refs["edit"].showInsertAndBindOrg(this.orgNode);
      }
    },
    handleDelete(row) {
      if (row.id) {
        this.$baseConfirm("你确定要删除当前项吗", null, async () => {
          const { msg } = await doDelete({ id: row.id });
          this.$baseMessage(msg, "success");
          await this.fetchData();
        });
      } else {
        if (this.selectRows.length > 0) {
          const ids = this.selectRows.map((item) => item.id).join();
          this.$baseConfirm("你确定要删除选中项吗", null, async () => {
            const { msg } = await doDeleteAll({ ids });
            this.$baseMessage(msg, "success");
            await this.fetchData();
          });
        } else {
          this.$baseMessage("未选中任何行", "error");
          return false;
        }
      }
    },
    async handleEnableAccount(row) {
      const enable = row.enable;
      if (row.enable === "0") row.enable = "1"
      else if (row.enable === "1") row.enable = "0"

      if (row.id) {
        const { msg } = await doEnableAccount({
          userId: row.id,
          enabled: enable
        });
        row.enable = enable;
        this.$baseMessage(msg, "success");
      } else {
        this.$baseMessage("未选中任何行", "error");
      }
    },
    handleNodeClick(nodeData) {
      if (!isNull(nodeData)) {
        const nodeId = nodeData.id;
        if ("org_all" !== nodeId && "org_null" !== nodeId) {
          this.queryForm.orgIdGroup = nodeData.parentIds + "," + nodeId;
          this.orgNode = nodeData;
          this.treeSelection = [nodeId];
        } else {
          this.queryForm.orgIdGroup = nodeId;
          this.orgNode = null;
          this.treeSelection = [];
        }
      }
      this.queryData();
    },
    moreQuery() {
      this.moreQueryFlag = !this.moreQueryFlag;
    },
    queryData() {
      this.queryForm.pageNo = 1;
      this.fetchData();
    },
    async fetchData() {
      this.listLoading = true;
      const { data } = await getList(this.queryForm);
      if (!isNull(data)) {
        this.list = data.rows;
        this.total = data.total;
      }
      setTimeout(() => {
        this.listLoading = false;
      }, 300);
    },
    async fetchOrgData() {
      this.treeLoading = true;
      const { data } = (await getTreeByDefWithUserToLike());
      if (!isNull(data)) {
        // 确保数据结构正确
        this.orgData = data.map(item => ({
          id: item.id,
          orgName: item.orgName,
          parentIds: item.parentIds,
          children: Array.isArray(item.children) ? item.children.map(child => ({
            id: child.id,
            orgName: child.orgName,
            parentIds: child.parentIds,
            children: child.children || []
          })) : []
        }));

        console.log('处理后的组织数据:', JSON.parse(JSON.stringify(this.orgData)));
      }
      setTimeout(() => {
        this.treeLoading = false;
      }, 300);
    },
    async getCurrUser() {
      this.listLoading = true;
      const { data } = await getUserInfo();
      if (!isNull(data)) {
        this.userInfo = Object.assign({}, data);
        setTimeout(() => {
          this.listLoading = false;
        }, 300);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.userManagement-container {
  padding: 16px;
  background-color: rgb(var(--v-theme-background));

  :deep(.v-card) {
    border-radius: 8px;
  }

  :deep(.v-data-table) {
    background: transparent !important;
  }

  :deep(.v-btn) {
    text-transform: none;
  }

  .add-user-btn {
    position: fixed;
    bottom: 24px;
    right: 24px;
    z-index: 100;
  }
}
</style>
